define(function(require) {
    require('fileuploader');
    require('jq_form');
    require('formvalidator');
    require('zhiphp');
    require('validate');
    require('artdialog');
    //日期控件
    require('jqui_extend_slideraccess');
    require('jqui_extend_timepicker');
    require('jqui_lang_datepicker');
    require('jqui_datepicker');

    var Base = require('common/base/object');

    _.defaults(window._global, {
        assets: _global.root + "app/Tpl/" + _global.g + "/public"
    });

    return Base.extend({
        dialog: dialog,
        /*
         初始化
         */
        initialize: function(params) {
            var _this = this;
            Base.prototype.initialize.apply(this, [params]);
            if (_global.a == 'edit') {
                $('#info_form').append("<input type='hidden' name='referrer' value='" + document.referrer + "'/>");
            }
            _this.bindEvents();
            _this.init_input();
            if (_this['page_' + _global.a]) {
                _this['page_' + _global.a]();
            }
        },
        /*
         事件绑定
         */
        bindEvents: function() {
            var _this = this;
            //AJAX请求效果
            $('#J_ajax_loading').ajaxStart(function() {
                $(this).show();
            }).ajaxSuccess(function() {
                $(this).hide();
            });

            //确认操作
            $('.J_confirmurl').bind('click', function() {
                var $this = $(this);
                var uri = $this.data('uri');
                var acttype = $this.data('acttype');
                var title = ($this.data('title') != undefined) ? $this.data('title') : _global.lang.confirm_title;
                var msg = $this.data('msg');
                var callback = $this.data('callback');
                if (acttype == 'batch_action') {
                    $('.J_checkitem').attr("checked", false);
                    $('.J_checkitem[value="' + $this.data('row_id') + '"]').attr("checked", 'checked');
                    $('input[data-tdtype="batch_action"]').trigger('click');
                    dialog.get($this.data('id')).title($this.data('title'));
                    return;
                }
                dialog({
                    title: title,
                    content: msg,
                    padding: '10px 20px',
                    lock: false,
                    ok: function() {
                        if (acttype == 'ajax') {
                            $.getJSON(uri, function(result) {
                                if (result.status == 1) {
                                    $.zhiphp.tip({
                                        content: result.msg
                                    });
                                    if (callback != undefined) {
                                        eval(callback + '(self)');
                                    } else {
                                        window.location.reload();
                                    }
                                } else {
                                    $.zhiphp.tip({
                                        content: result.msg,
                                        icon: 'error'
                                    });
                                }
                            });
                        } else {
                            location.href = uri;
                        }
                    },
                    cancel: function() {}
                }).show();
            });

            //附件预览
            $('.J_attachment_icon').bind('mouseover', function() {
                var ftype = $(this).attr('file-type');
                var rel = $(this).attr('file-rel');
                switch (ftype) {
                    case 'image':
                        if (!$(this).find('.attachment_tip')[0]) {
                            $('<img class="attachment_tip" width="160" height="80" src="' + rel + '" />').prependTo($(this)).fadeIn();
                        } else {
                            $(this).find('.attachment_tip').fadeIn();
                        }
                        break;
                }
            }).bind('mouseout', function() {
                $('.attachment_tip').hide();
            });
        },
        /*
         初始化弹层
         */
        initFormDialog: function(params) {
            var _this = this;

            if (_.empty(params)) {
                params = function() {};
            }
            if (_.isFunction(params)) {
                params = {
                    loadAfter: params
                };
            }

            //弹窗表单
            $('.J_showdialog').bind('click', function() {
                var $this = $(this);
                var dtitle = _.empty($this.data('title')) ? '标题' : $this.data('title');
                var did = $this.data('id');
                var duri = $this.data('uri');
                var dwidth = _.intval($this.data('width'));
                var dheight = _.intval($this.data('height'));
                var dpadding = ($this.data('padding') != undefined) ? $this.data('padding') : '';
                var dcallback = $this.data('callback');

                if (_this.dialog.get(did)) {
                    _this.dialog.get(did).remove();
                }
                var $$ = function(selector) {
                    if (_.empty(selector)) {
                        return $('#artdialog-' + did);
                    } else {
                        return $('#artdialog-' + did + " " + selector);
                    }
                };
                $.getJSON(duri, function(result) {
                    if (result.status != 1) {
                        console.log('弹层内容获取失败！');
                        return;
                    }
                    var d = _this.dialog({
                        id: did,
                        zIndex: 100,
                        title: dtitle,
                        content: result.data,
                        width: dwidth ? dwidth : 'auto',
                        // height: dheight ? dheight : 'auto',
                        padding: dpadding,
                        lock: false,
                        ok: function() {
                            var $form = $$('form');
                            var validator = $form.validate();
                            if (validator.form()) {
                                d.close();
                                var method = _.trim($form.attr('method'));
                                $.ajax({
                                    url: $form.attr('action'),
                                    dataType: 'json',
                                    data: $form.serializeJson(),
                                    type: (_.empty(method) ? "POST" : method.toUpperCase()),
                                    success: function(resp) {
                                        if (resp.status == 1) {
                                            $.zhiphp.tip({
                                                content: resp.msg
                                            });
                                            window.location.reload();
                                        } else {
                                            $.zhiphp.tip({
                                                content: resp.msg,
                                                icon: 'alert'
                                            });
                                            d.show();
                                            return false;
                                        }
                                    },
                                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                                        console.log(textStatus);
                                    }
                                });
                            }
                            return false;
                        },
                        cancel: function() {}
                    });
                    d.show();
                    //ui-dialog-content出现""
                    $('.ui-dialog-content').each(function() {
                        $(this).html(_.sprintf('<div class="dialog_content">%s</div>', $('.ui-dialog-content .dialog_content').html()));
                    });
                    params.loadAfter.apply(_this, [$$]);
                    _this.create_datepicker();
                });
            });
        },
        /*
         表单验证
         */
        validate: function() {
            var validator = $('form').validate({});
            //console.log('go');
            return validator;
        },
        /*
         创建编辑器
         说明：可以直接传#id
         */
        kindEditor: function(params) {
            var _this = this;
            if (_.isString(params)) {
                params = {
                    sel: params
                };
            }
            KindEditor.create(params.sel, _.extend({
                uploadJson: _.U({
                    m: 'attachment',
                    a: 'editer_upload'
                }),
                fileManagerJson: _.U({
                    m: 'attachment',
                    a: 'editer_manager'
                }),
                allowFileManager: true
            }, _.omit(params, 'sel')));
        },
        /*
         创建上传组件
         */
        uploader: function(params) {
            var _this = this;
            params = _.defaults(params, {
                type: 'image',
                action: {}
            });
            var ext = {
                image: ['jpg', 'gif', 'jpeg', 'png', 'bmp', 'pdg']
            };
            new qq.FileUploaderBasic({
                allowedExtensions: ext[params.type],
                button: document.getElementById(params.btn.attr('id')),
                multiple: false,
                action: _.U(_.extend({
                    m: _global.m,
                    a: 'ajax_upload_img'
                }, params.action)),
                inputName: params.input.attr('name'),
                forceMultipart: true, //用$_FILES
                messages: {
                    typeError: _global.lang.upload_type_error,
                    sizeError: _global.lang.upload_size_error,
                    minSizeError: _global.lang.upload_minsize_error,
                    emptyError: _global.lang.upload_empty_error,
                    noFilesError: _global.lang.upload_nofile_error,
                    onLeave: _global.lang.upload_onLeave
                },
                showMessage: function(message) {
                    $.zhiphp.tip({
                        content: message,
                        icon: 'error'
                    });
                },
                onSubmit: function(id, fileName) {
                    params.btn.addClass('btn_disabled').find('span').text(_global.lang.uploading);
                },
                onComplete: function(id, fileName, result) {
                    params.btn.removeClass('btn_disabled').find('span').text(_global.lang.upload);
                    if (result.status == '1') {
                        params.input.val(result.data);
                    } else {
                        $.zhiphp.tip({
                            content: result.msg,
                            icon: 'error'
                        });
                    }
                }
            });
        },
        init_input: function() {
            $('.text,.J_tip').each(function() {
                $this = $(this);
                if (!empty($(this).val())) return;

                var tag = $this[0].tagName;
                if (tag == 'INPUT') {
                    $this.val($this.attr('data-default'));
                } else if (tag == 'TEXTAREA') {
                    $this.html($this.attr('data-default'));
                }
                $this.css('color', '#666');
            }).click(function() {
                if ($(this).attr('data-default') == $(this).val()) {
                    $(this).val('');
                    $this.css('color', '#000');
                }
            }).blur(function() {
                $this = $(this);
                if ($this.attr('data-default') == $this.val() || $.trim($this.val()) == '') {
                    $this.val($this.attr('data-default'));
                    $this.css('color', '#666');
                }
            });
        },
        /*
         创建日期组件
         */
        create_datepicker: function() {
            var DATE_PICKER_OPT = {
                showWeek: true,
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
                showButtonPanel: true,
                timeFormat: 'HH:mm:ss',
                yearRange: '-100:+10',
                stepHour: 1,
                stepMinute: 1,
                stepSecond: 1,
                timeOnlyTitle: '1',
                timeText: '时间',
                hourText: '小时',
                minuteText: '分钟',
                secondText: '秒',
                currentText: '现在',
                closeText: '关闭'
            };
            if (_.empty($.fn.datepicker)) {
                console.log("$.fn.datepicker为空！");
            }
            $(".J_date_picker").each(function() {
                var opt = DATE_PICKER_OPT,
                    is_short = $(this).hasClass('short');

                if ($(this).attr("data-minDate")) {
                    opt.onClose = function(selectedDate) {
                        if (is_short) {
                            $($(this).attr("data-minDate")).datepicker("option", "minDate", selectedDate);
                        } else {
                            $($(this).attr("data-minDate")).datetimepicker("option", "minDate", selectedDate);
                        }
                    };
                }
                if ($(this).attr("data-maxDate")) {
                    opt.onClose = function(selectedDate) {
                        if (is_short) {
                            $($(this).attr("data-maxDate")).datepicker("option", "maxDate", selectedDate);
                        } else {
                            $($(this).attr("data-maxDate")).datetimepicker("option", "maxDate", selectedDate);
                        }
                    };
                }
                if (is_short) {
                    $(this).datepicker(opt);
                } else {
                    $(this).datetimepicker(opt);
                }
            });
        }
    });
});